package com.whfp.coky.ui.task.vm.rfid

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder
import com.whfp.coky.api.RequestBodyBuild
import com.whfp.coky.ui.base.BaseActivity
import com.whfp.coky.ui.base.vm.RFIDVM
import com.whfp.coky.ui.task.model.SearchCodePrintBean
import com.whfp.coky.utils.InfoTool
import com.whfp.coky.utils.LogUtil
import com.whfp.coky.utils.RFIDBaseUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *
 *
 * created by coky on 2022/3/1
 */
class WriteVM: RFIDVM() {


    var searchCodePrintBeanLD = MutableLiveData<SearchCodePrintBean>()

    override fun observe(activity: BaseActivity<*, *>, owner: LifecycleOwner) {
        super.observe(activity, owner)
        /**
         *  获取到http上的二维码信息，
         *  完成界面展示，提取content，准备写入
         * @param bean
         */
        searchCodePrintBeanLD.observe(owner, Observer {
//            isEnable = true
            if (it.info.isEmpty()){
                activity.toast("需要写入的内容为空!")
            }else{
                activity.showDialog()
                content = it.info[0].ewm
                viewModelScope.launch {
                    var qrBitmap = QRCodeEncoder.syncEncodeQRCode(content, 420)
                    while (qrBitmap == null){
                        LogUtil.e("生成二维码中...")
                        delay(300L)
                    }
                    activity.hideDialog()
                    vBinding.rfidItem.tvCode.text = it.info[0].name
                    vBinding.rfidItem.ivQrCode.setImageBitmap(qrBitmap)
                }
            }
        })
    }

    //    写卡，获取http卡片信息展示
    override fun doUpdate(activity: BaseActivity<*, *>) {
            isEnable = false
            activity.showDialog()

    }


    //    查询二维码信息
    fun doSearchQrCode(id:String){
        val map = HashMap<String, String>()
        map["detailId"] = id
        map["mac"] = InfoTool.buildPhoneMac()
        map["sn"] =InfoTool.buildPhoneMac()
        launch({httpUtil.doSearchQrCode(body = RequestBodyBuild.buildBodyByMap(map))},searchCodePrintBeanLD,true)
    }



    fun checkContent(activity: BaseActivity<*, *>):ByteArray?{
        val datas = when{
            content.length > 12 -> RFIDBaseUtil.getHexByteArray(content)
            else -> content.substring(0,12).toByteArray()
        }
        if (datas.size>12){
            activity.toast("处理后要写入的内容大于12个字节，无法写入")
            return null
        }
        return datas
    }

    fun write2Tag(activity: BaseActivity<*, *>){
        checkContent(activity)?.let {data->
            activity.showDialog("写卡中,请稍后...")
            currentRssiMax?.id?.let {
               val isWriteSuccess =  myRFID.writeTagData(
                    it,
                    RFIDBaseUtil.getHexByteArray("00000000"),
                    1,
                    4,
                    data.size,
                    data
                )
                if (isWriteSuccess){
                    doCommit()
                }else{
                    activity.toast("写卡失败..")
                }
            }

        }
    }

    /**
     * 连接网络   提交写卡任务
     */
    fun doCommit(){

    }

}